# 百度AI机器人对话
import requests
import json

APP_ID = '18453110'
API_KEY = '7Ev7K3wNxiAK9S8y4XBPllUx'
SECRET_KEY = 'iQz8me6bPy9FQ1xsT2ueqv2oeiOz8Fnq'


def getBaiDuAK():
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + API_KEY + '&client_secret=' + SECRET_KEY
    r = requests.get(host)
    return r.json()['access_token']


def baiduApi(text, session_id):
    global access_token
    url = 'https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=' + access_token
    query = text
    # 下面的log_id在真实应用中要自己生成，可是递增的数字
    log_id = '7758521'
    # 下面的user_id在真实应用中要是自己业务中的真实用户id、设备号、ip地址等，方便在日志分析中分析定位问题
    user_id = '222333'
    # 下面要替换成自己的bot_id，是你的技能ID！！
    bot_id = '60795'

    request = {'bernard_level': 1, 'user_id': '222333', 'query': text,
               'query_info': {'asr_candidates': [], 'source': 'KEYBOARD', 'type': 'TEXT'}}
    post_data = {'service_id': 'S26765', 'session_id': session_id, 'log_id': '7758521',
                 'version': '2.0', 'request': request}
    headers = {'Content-Type': 'application/json'}

    response = requests.post(url, json=post_data, headers=headers)

    if response.ok:
        res_text = json.loads(response.text)
        if res_text['error_code'] == 0:
            response_list = res_text['result']['response_list']
            action_list = response_list[0]['action_list']
            return res_text['result']['session_id'], action_list[0]['say']


global access_token  # 在使用前初次声明
access_token = getBaiDuAK()
# bot.file_helper.send('[奸笑][奸笑]')
print('欣欣AI已经启动')

ret = baiduApi("今天天气", "")
print('[发送]:' + str(ret))
ret = baiduApi("成都", ret[1])

print('[发送]:' + str(ret))
